﻿using System;
using System.Linq;
using System.Data.Linq;
using System.Collections.Generic;
using System.Text;
using HR.Appointments.DataLayer;

namespace HR.Appointments.Service.DataAccessLayer.DLinq
{
    internal class ActivityDAO : IActivityDAO
    {
        #region IActivityDAO Members
        public List<ActivityEntity> GetByCompany(int companyId)
        {
            var result = new List<ActivityEntity>();
            using (DAODataContext ctx = new DAODataContext())
            {
                var sql = from data in ctx.Activities
                          where data.CompanyId == companyId
                          select data;

                foreach (HR.Appointments.DataLayer.Activity table in sql)
                {
                    result.Add(ActivityEntity.Load(table));
                }
            }
            return result;
        }

        public ActivityEntity GetInstance(int activityId)
        {
            using (DAODataContext ctx = new DAODataContext())
            {
                var sql = from data in ctx.Activities
                          where data.ActivityId == activityId
                          select data;

                return ActivityEntity.Load(sql.FirstOrDefault());
            }
        }

        public void Insert(ActivityEntity activity)
        {
            using (DAODataContext ctx = new DAODataContext())
            {
                ctx.Activities.InsertOnSubmit(activity.ToData(null));
                ctx.SubmitChanges();
            }
        }

        public void Update(ActivityEntity activity)
        {
            using (DAODataContext ctx = new DAODataContext())
            {
                var sql = from data in ctx.Activities
                          where data.ActivityId == activity.ActivityId
                          select data;

                Activity row = activity.ToData(sql.FirstOrDefault());
                ctx.SubmitChanges();
            }
        }

		public void Delete(int companyId, int activityId)
		{
			using (DAODataContext ctx = new DAODataContext())
			{
				var sql = from data in ctx.Activities
						  where data.CompanyId == companyId
						  && data.ActivityId == activityId
						  select data;

				if (sql.Count() != 0)
				{
					ctx.Activities.DeleteOnSubmit(sql.FirstOrDefault());
					ctx.SubmitChanges();
				}
			}
        }
        #endregion
    }
}
